package com.frinder.netty.chat;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by kiktech on 2017/8/3.
 */
public class SimpleChatServerHandler extends SimpleChannelInboundHandler<String> { // (1)

    private final Logger logger = LoggerFactory.getLogger(getClass());

    public static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {  // (2)
        Channel incoming = ctx.channel();
        String message = String.format("[SERVER] - %s come in !\n", incoming.remoteAddress());
        logger.info("{}", message);
        // Broadcast a message to multiple Channels
        channels.writeAndFlush(message);

        channels.add(ctx.channel());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {  // (3)
        Channel incoming = ctx.channel();

        String message = String.format("[SERVER] - %s leave !\n", incoming.remoteAddress());
        logger.info("{}", message);

        // Broadcast a message to multiple Channels
        channels.writeAndFlush(message);

        // A closed Channel is automatically removed from ChannelGroup,
        // so there is no need to do "channels.remove(ctx.channel());"
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String s) throws Exception { // (4)
        Channel incoming = ctx.channel();
        for (Channel channel : channels) {
            if (channel != incoming) {
                channel.writeAndFlush(String.format("[%s] %s\n", incoming.remoteAddress(), s));
            } else {
                channel.writeAndFlush(String.format("[you] %s\n", s));
            }
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception { // (5)
        Channel incoming = ctx.channel();
        logger.info("SimpleChatClient: {} online!", incoming.remoteAddress());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception { // (6)
        Channel incoming = ctx.channel();
        logger.info("SimpleChatClient: {} offline!", incoming.remoteAddress());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (7)
        Channel incoming = ctx.channel();
        logger.info("SimpleChatClient: {} error!", incoming.remoteAddress());
        // 当出现异常就关闭连接
        cause.printStackTrace();
        ctx.close();
    }
}
